package com.itheimajdbc;
import org.junit.Test;
import java.sql.*;

//课本案例
public class jdbcdemo_anli {
    //执行DQL语句
    public static void main(String[] args) throws Exception{
        Statement stmt = null;
        ResultSet rs = null;
        Connection conn = null;
        try{
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //连接数据库连接
            String url = "jdbc:mysql://localhost:3306/mysql";
            String username = "root";
            String password = "123456";
            conn = DriverManager.getConnection(url,username,password);
            //通过Connection对象获取Statement对象
            stmt = conn.createStatement();
            //使用Statement执行sql语句
            String sql = "select*from demo";
            rs = stmt.executeQuery(sql);
            //操作ResultSet结果集
            System.out.println("id |  name |  money");
            while(rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String psw = rs.getString("money");
                System.out.println(id +"  |    "+name+"   |    "+ psw + "  |    ");
            }
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }finally {
            //释放资源
            if(rs !=null){
                try{
                    rs.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
                rs = null;
            }
            if(stmt != null){
                try{
                    stmt.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
                stmt =null;
            }
            if(conn !=null){
                try{
                    conn.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
                conn = null;
            }
        }
    }
}